<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="../../vue.js"></script>
  <script src="../../vuex.js"></script>
</head>

<body>
  <div id="app">
    <counter-btn type="decrement"></counter-btn>
    <counter-span></counter-span>
    <counter-btn type="increment"></counter-btn>

  </div>

  <script>

    Vue.component('counter-span', {
      template: `<span>{{$store.state.count}}</span>`
    })


    Vue.component('counter-btn', {
      props: ['type'],
      template: `<button @click="handleClick">{{btntext}}</button>`,
      computed: {
        btntext() {
          return this.type === 'decrement' ? '-' : '+'
        }
      },
      methods: {
        handleClick() {
          if (this.type === 'increment') {
            // this.$store.state.count++;
            // this.$store.commit('increment')
            //调用mutations 下的方法
            // store.commit('increment', { num: 3 })
            //调用actions下的方法
            store.dispatch('add', { num: 3 })
          } else {
            // this.$store.state.count--;
            this.$store.commit('decrement', { num: 2 })
          }
        }
      }
    })


    var store = new Vuex.Store({
      //相当于自定义组件中的data
      state: {
        count: 0
      },
      //同步数据的修改
      mutations: {
        increment(state, obj) {
          state.count += obj.num;
        },
        decrement(state, obj) {
          state.count -= obj.num;
        }
      },
      //异步数据
      actions: {
        add(obj1, obj) {
          console.log(obj1)
          setTimeout(() => {
            obj1.commit('increment', obj)
          }, 3000)
        }
      }
    })

    var vm = new Vue({
      store,
      el: "#app"
    })

  </script>

</body>

</html>